﻿using BaseBll;
using BaseWebApi.App_Start;
using BaseWebApi.Common;
using BaseWebApi.Models;
using Common;
using Models;
using Models.QueryParam;
using System;
using System.Collections.Generic;
using System.Data;
using System.Net.Http;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Http;

namespace BaseWebApi.Controllers
{
    /// <summary>
    /// 收货管理
    /// </summary>
    [ControllerGroup(groupName: "PurchaseGet", useage: "采购管理-收货管理")]
    public class PurchaseGetController : BaseController
    {
        private JWTPlayloadInfo playload;

        /// <summary>
        /// 分页查询收货单
        /// </summary>
        /// <param name="queryParams">查询参数对象</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetPageList([FromUri] PurchaseGetQuery queryParams)
        {
            string msg = "";
            string strWhere = PurchaseGetBll.Instance.GetListWhere(queryParams,ref msg);     
            
            if(strWhere == null)
            {
                JsonHelper.FailJson(msg);
            }

            DataTable dt = PurchaseGetBll.Instance.GetPageList(queryParams.PageSize, queryParams.PageIndex, strWhere, "PG_Date DESC", out int records);
            int totalPages = PageHelper.GetPageCount(queryParams.PageSize, records);
            return JsonHelper.SuccessJson(CommonOperation.DataTable2JArray(dt), queryParams.PageIndex, totalPages, records);
        }

        /// <summary>
        /// 查询数据集合
        /// </summary>
        /// <param name="queryParams"></param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetList([FromUri] PurchaseGetQuery queryParams)
        {
            string msg = "";
            string strWhere = PurchaseGetBll.Instance.GetListWhere(queryParams, ref msg);

            if (strWhere == null)
            {
                JsonHelper.FailJson(msg);
            }

            List<PurchaseGetHead> list = PurchaseGetBll.Instance.GetList(strWhere);

            return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
        }

        /// <summary>
        /// 根据ID获取实体对象
        /// </summary>
        /// <param name="ID">数据表ID</param>
        /// <returns></returns>
        [HttpGet]
        public HttpResponseMessage GetModel(int ID)
        {
            if (ID > 0)
            {
                PurchaseGetHead model = PurchaseGetBll.Instance.GetModelById(ID);
                if (model != null)
                {
                    // 查询文件
                    DataTable dt = UploadBll.Instance.GetFiles(ID, "PurchaseGet");
                    model.FileList = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                    return JsonHelper.SuccessJson(JsonHelper.ModelToJObject(model));
                }
                else
                {
                    return JsonHelper.FailJson("数据不存在");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误");
            }
        }

        /// <summary>
        /// 新增收货单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage AddPurchaseGet([FromBody] PurchaseGetHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                //验证各字段合法性
                string msg = "";
                bool isOk = PurchaseGetBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = PurchaseGetBll.Instance.AddPurchaseGet(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }
                        LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Add, "新增收货单");
                        return JsonHelper.SuccessJson("新增成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Add, "新增收货单");
                        return JsonHelper.FailJson("新增失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Add, "新增收货单");
                throw;
            }
        }

        /// <summary>
        /// 修改收货单
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdatePurchaseOrder([FromBody] PurchaseGetHead model)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (model.ID <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            try
            {
                bool isExist = PurchaseGetBll.Instance.IsExist(" and ID=" + model.ID);
                if (!isExist)
                {
                    return JsonHelper.ErrorJson("不存在该数据");
                }
                //验证各字段合法性
                string msg = "";
                bool isOk = PurchaseGetBll.Instance.VerifyModel(model, ref msg);
                if (isOk)
                {
                    bool res = PurchaseGetBll.Instance.UpdatePurchaseGet(model);
                    if (res)
                    {
                        // 更新文件信息
                        if (model.FileList != null && model.FileList.Count > 0)
                        {
                            UploadBll.Instance.Update(model.ID, model.FileList);
                        }
                        LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Edit, "修改收货单");
                        return JsonHelper.SuccessJson("修改成功");
                    }
                    else
                    {
                        LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Edit, "修改收货单");
                        return JsonHelper.FailJson("修改失败");
                    }
                }
                else
                {
                    return JsonHelper.FailJson(msg);
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Edit, "修改收货单");
                throw;
            }
        }

        /// <summary>
        /// 删除收货单（状态为2：暂存时才可删除）
        /// </summary>
        /// <param name="id">ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePurchaseGet(int id)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            try
            {
                if (id <= 0)
                {
                    return JsonHelper.FailJson("参数错误！");
                }
                else
                {
                    // 判断状态（状态为2：暂存时才可删除）
                    if (!PurchaseGetBll.Instance.IsExist(" and ID=" + id + " and PG_AuditStatus=2 "))
                    {
                        return JsonHelper.FailJson("该收货单正在使用中，不允许删除！");
                    }
                    else
                    {
                        bool result;
                        // 先删除相关图片
                        DataTable dt = UploadBll.Instance.GetFiles(id, "PurchaseGet");
                        if (dt.Rows.Count > 0)
                        {
                            List<FileData> files = CommonOperation.ConvertDataTableToModelList<FileData>(dt);
                            string fid = "";
                            for (int i = 0; i < files.Count; i++)
                            {
                                if (string.IsNullOrEmpty(fid))
                                {
                                    fid = "'" + files[i].RelationId + "'";
                                }
                                else
                                {
                                    fid += ",'" + files[i].RelationId + "'";
                                }
                            }
                            bool res = UploadBll.Instance.DeleteFiles(fid, "PurchaseGet", files);
                            if (res)
                            {
                                LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                                result = PurchaseGetBll.Instance.DeletePurchaseGet(id);
                                if (result)
                                {
                                    LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除收货单");
                                    return JsonHelper.SuccessJson("删除成功");
                                }
                                else
                                {
                                    LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除收货单");
                                    return JsonHelper.SuccessJson("删除失败");
                                }
                            }
                            else
                            {
                                LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除所有文件(HeadID:" + id + ")");
                                return JsonHelper.FailJson("删除文件失败");
                            }
                        }
                        else
                        {
                            result = PurchaseGetBll.Instance.DeletePurchaseGet(id);
                            if (result)
                            {
                                LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除收货单");
                                return JsonHelper.SuccessJson("删除成功");
                            }
                            else
                            {
                                LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除收货单");
                                return JsonHelper.SuccessJson("删除失败");
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除收货单");
                throw;
            }
        }

        /// <summary>
        /// 修改审核状态
        /// </summary>
        /// <param name="id"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage UpdateStatus(int id, int status)
        {
            playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (id <= 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            if (status != 1 && status != 2 && status != 0)
            {
                return JsonHelper.ErrorJson("参数错误");
            }

            string strStatus = "";

            if (status == 0)
            {
                strStatus = "审批中";
            }
            if (status == 1)
            {
                strStatus = "审批通过";
            }
            if (status == 2)
            {
                strStatus = "暂存";
            }

            try
            {
                // 判断是否存在该记录
                PurchaseGetHead model = PurchaseGetBll.Instance.GetModelById(id);
                if (model == null)
                {
                    return JsonHelper.ErrorJson("数据不存在，请刷新重试");
                }
                if(model.PG_AuditStatus == 1)
                {
                    return JsonHelper.ErrorJson("该单据已审核通过");
                }

                int result = PurchaseGetBll.Instance.UpdateStatus(id, status);
                if (result > 0)
                {
                    // 如果状态修改为 1：已审批。修改采购申请的到货数量
                    if (status == 1)
                    {
                        PurchaseGetBll.Instance.UpdRequestWithAudit(model.ItemList,model.PG_OrderID);
                    }
                    LogHelper.LogAction(playload, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.SuccessJson("状态修改成功");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                    return JsonHelper.FailJson("状态修改失败");
                }
            }
            catch (Exception ex)
            {
                LogHelper.LogError(playload, ex, Constant.SysModule.PurchaseOrder, Constant.ActionEnum.Edit, strStatus);
                throw;
            }
        }


        #region 上传文件相关

        /// <summary>
        /// 上传文件
        /// </summary>
        /// <returns></returns>
        public HttpResponseMessage UploadFile()
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];

            List<FileData> list = new List<FileData>();
            HttpFileCollection files = HttpContext.Current.Request.Files;
            foreach (var key in files.AllKeys)
            {
                HttpPostedFile postedFile = files[key];
                if (!string.IsNullOrEmpty(postedFile.FileName))
                {
                    // file.SaveAs(HttpContext.Current.Server.MapPath("~/imgcoll/") + file.FileName);
                    //文件扩展名，不含“.”
                    string fileExt = Utils.GetFileExt(postedFile.FileName);

                    // 文件类型
                    Regex regex = new Regex(@"pdf|doc|docx|xlsx|xls");
                    bool isMatch = regex.IsMatch(fileExt);
                    if (!isMatch)
                    {
                        return JsonHelper.ErrorJson("文件类型不匹配");
                    }

                    FileData model = UploadHelper.SaveFilePic(postedFile, UploadHelper.uploadPath + "files/pc/purchase/get/" + DateTime.Now.ToString("yyyyMMdd"), DateTime.Now.ToString("yyyyMMddHHmmss"));

                    // 文件类型
                    model.FileType = fileExt;

                    // 关联表
                    model.RelationTable = "PurchaseGet";

                    if (model != null)
                    {
                        list.Add(model);
                    }
                    else
                    {
                        continue;
                    }
                }
            }
            if (list.Count > 0)
            {
                bool result = UploadBll.Instance.AddList(list);
                if (result)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.SuccessJson(JsonHelper.ListToJArray(list));
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Upload, "上传文件");
                    return JsonHelper.ErrorJson("上传失败，稍后重试");
                }
            }
            else
            {
                return JsonHelper.ErrorJson("没有匹配的文件类型");
            }
        }

        /// <summary>
        /// 根据文件ID删除文件
        /// </summary>
        /// <param name="fileID">文件ID</param>
        /// <returns></returns>
        [HttpPost]
        public HttpResponseMessage DeletePic(string fileID)
        {
            JWTPlayloadInfo playload = (JWTPlayloadInfo)Request.Properties["playload"];
            if (string.IsNullOrEmpty(fileID))
            {
                return JsonHelper.ErrorJson("参数错误");
            }
            FileData model = UploadBll.Instance.GetFileByID(fileID);
            if (model != null)
            {
                bool res = UploadBll.Instance.DeleteFilesByID(fileID, model);
                if (res)
                {
                    LogHelper.LogAction(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.SuccessJson("删除成功！");
                }
                else
                {
                    LogHelper.LogWarn(playload, Constant.SysModule.PurchaseGet, Constant.ActionEnum.Delete, "删除文件(ID:" + fileID + ")");
                    return JsonHelper.FailJson("删除失败！");
                }
            }
            else
            {
                return JsonHelper.FailJson("参数错误！,文件不存在");
            }
        }

        #endregion 上传文件相关

    }
}
